﻿using UnityEngine;
using System.Collections;
using Pathfinding;
using Controller.ServiceContract;

namespace Services.AI
{
    public class ServicesNPC : IServicesNPC
    {
        private ListPlaces list;
        private int MaxPlaces = 0;
        private int iSelectPath = 0;
        private Vector3 dir;

        /// <summary>
        /// Constructor of the class
        /// </summary>
        public ServicesNPC(){}

        /// <summary>
        /// Set the list of places avalible for the IA
        /// </summary>
        /// <param name="listP">List of Places</param>
        public void SetListPlaces(ListPlaces listP)
        {
            list = listP;
            MaxPlaces = list.MaxPlaces;
        }

        /// <summary>
        /// Set the initialize path for the NPC
        /// </summary>
        /// <param name="NPC">CLass citizen Model associate to the object</param>
        public void StartPath(CitizenModel NPC)
        {
            //_cmNPC = NPC;
            iSelectPath = Random.Range(0, MaxPlaces);
            NPC.GetSeeker().StartPath(NPC.GetModelCitizen().transform.position, list.places[iSelectPath], NPC.GetCitizen().OnPathComplete);
        }

        /// <summary>
        /// Make the NPC move towards, one of the list of paths
        /// </summary>
        /// <param name="NPC">CLass citizen Model associate to the object</param>
        public void MoveNPC(CitizenModel NPC)
        {
            if (NPC.GetCitizen().path == null)
            {
                return;
            }
            if (NPC.GetCitizen().CurrentWayPoint >= NPC.GetCitizen().path.vectorPath.Count)
            {
                iSelectPath = Random.Range(0, MaxPlaces);
                NPC.GetSeeker().StartPath(NPC.transform.position, list.places[iSelectPath], NPC.GetCitizen().OnPathComplete);
                return;
            }
            dir = (NPC.GetCitizen().path.vectorPath[NPC.GetCitizen().CurrentWayPoint] - NPC.GetModelCitizen().transform.position).normalized;
            dir *= NPC._speed * Time.fixedDeltaTime;
            NPC.GetCitizen().Walk(dir);
            NPC.GetCitizen().RotateTowards(dir, NPC.GetTurningSpeed());
            if (Vector3.Distance(NPC.GetModelCitizen().transform.position, NPC.GetCitizen().path.vectorPath[NPC.GetCitizen().CurrentWayPoint]) < NPC._nextWaypointDistance)
            {
                NPC.GetCitizen().CurrentWayPoint = NPC.GetCitizen().CurrentWayPoint + 1;
                return;
            }
        }
    }
}